package com.networknt.rpc.router;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import com.networknt.config.Config;
import com.networknt.server.StartupHookProvider;
import com.zaxxer.hikari.HikariDataSource;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class DbStartupHookProvider implements StartupHookProvider {
    public static final String DATA_SOURCE = "datasource";
    public static Map<String, DataSource> dbMap = new HashMap<>();

	@Override
    public void onStartup() {
        Map<String, Object> dataSourceMap = (Map<String, Object>) Config.getInstance().getJsonMapConfig(DATA_SOURCE);
        int size = dataSourceMap == null ? 0 : dataSourceMap.size();
        System.out.println("DbStartupHookProvider datasource size " + size);
        if(size == 0) return;
        dataSourceMap.forEach((k, v) -> {
        	initDataSource(k, v);
        });
    }
	/** 数据库可以gserver统一配置datasource.yml，也可以gservice独立配置gservice.yml，驱动driver需加入依赖目录 */
	@SuppressWarnings("unchecked")
	public static void initDataSource(String k, Object v) {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(((Map<String, String>) v).get("jdbcUrl"));
        ds.setUsername(((Map<String, String>) v).get("username"));
        ds.setPassword(((Map<String, String>) v).get("password"));
        Map<String, ?> configParams = (Map<String, ?>) ((Map<String, Object>) v).get("parameters");
        configParams.forEach((p, q) -> ds.addDataSourceProperty(p, String.valueOf(q)));
        dbMap.put(k, ds);
        try (Connection conn = ds.getConnection()) {
            log.info("datasource={} is ok", k);
        } catch (Throwable e) {
            log.warn("fail to connect datasource={} msg={}", k, e.getMessage());
        }
        HybridShutdownHookProvider.add(ds);
	}
}
